//
//  PageScrollVertical.m
//  ebook
//
//  Created by mt on 16/8/8.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "PageScrollVerticalView.h"
#import "ReaderGlobalModel.h"
#import "PageView.h"
#import "PageScrollFooterView.h"
#import "UIView+Extension.h"
#import <CoreText/CoreText.h>

#define kTextWidth (MTScreenW-[ReaderGlobalModel shareModel].readerConfig.padingLeft-[ReaderGlobalModel shareModel].readerConfig.padingRight)
#define kScrollHeight (MTScreenH-[ReaderGlobalModel shareModel].readerConfig.padingBottom_Updown-[ReaderGlobalModel shareModel].readerConfig.padingTop_Updown)

@interface PageScrollVerticalView ()<UIGestureRecognizerDelegate,UIScrollViewDelegate>{
    BOOL needResumeTimer;
}

@property (nonatomic, strong) PageView *curPageView;
@property (nonatomic, strong) PageView *bakPageView;
@property (nonatomic, strong) ChapterContent *curChapterContent;
@property (nonatomic, strong) ChapterContent *bakChapterContent;
@property (nonatomic, strong) PageScrollFooterView *footerView;
@property (nonatomic, strong) UITapGestureRecognizer *tapAction;

@property (nonatomic, strong) NSTimer *autoScrollReadingTimer;
@property (nonatomic) BOOL isForceStop;
@property (nonatomic, assign) float timerInterval;

@end

@implementation PageScrollVerticalView

- (instancetype)init {
    
    self = [super initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH)];
    if (self = [super init]) {
        
        self.bookmark = [[Bookmark alloc] init];
        self.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
        
        [self addSubview:self.scrollView];
        [self.scrollView addSubview:self.curPageView];
        [self.scrollView addSubview:self.bakPageView];
        
        _tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnPageView:)];
        _tapAction.delegate = self;
        [self addGestureRecognizer:_tapAction];
        [self addSubview:self.footerView];
    }
    self.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBgColor:) name:kChangePageColorNotification object:nil];
    
    return self;
}

- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, [ReaderGlobalModel shareModel].readerConfig.padingTop_Updown, MTScreenW, kScrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        _scrollView.decelerationRate = 0;//滑动速率
    }
    return _scrollView;
}

#pragma mark - PageView
- (PageView *)curPageView
{
    if (!_curPageView) {
        _curPageView = [self newPageView];
    }
    return _curPageView;
}

-(PageView *)bakPageView{
    if (!_bakPageView) {
        _bakPageView = [self newPageView];
    }
    return _bakPageView;
}

-(PageView *)newPageView{
    PageView *pageview = [[PageView alloc] init];
    pageview.backgroundColor = [UIColor clearColor];
    return pageview;
}

-(void)resetView{
    if(_curPageView.attributedText.length>0){
        [_curPageView removeFromSuperview];
        _curPageView = nil;
        [self.scrollView addSubview:self.curPageView];
    }
    if(_bakPageView.attributedText.length>0){
        [_bakPageView removeFromSuperview];
        _bakPageView = nil;
        [self.scrollView addSubview:self.bakPageView];
    }
}

-(void)updateBgColor:(NSNotification *)noti{//切换背景颜色时，需重新加载数据刷新文字颜色
    
    self.backgroundColor = [ReaderGlobalModel shareModel].readerConfig.ViewBgColor;
    
    [self.bakPageView setText:[self attributedString:self.bakChapterContent]];
    [self.curPageView setText:[self attributedString:self.curChapterContent]];
}

#pragma mark - 加载数据
-(void)loadPageCurrent:(ChapterContent *)cchapterContent pre:(ChapterContent *)pchapterContent next:(ChapterContent *)nchapterContent curentPercent:(float)cpercent direct:(int)direct{
    
    self.tapAction.enabled = YES;
    switch (direct) {
            
        case -1://往前
        {//往前翻时，前一章变成了当前章，当前章成为了下一章
            CGRect cFrame = [self frameOfChaptercontent:cchapterContent];
            CGRect nFrame = [self frameOfChaptercontent:nchapterContent];
            nFrame.origin.y = cFrame.size.height;
            self.bakPageView.frame = nFrame;
            self.curPageView.frame = cFrame;
            self.bakChapterContent = nchapterContent;
            self.curChapterContent = cchapterContent;
            [self loadView:self.bakPageView content:nchapterContent];
            [self loadView:self.curPageView content:cchapterContent];
            
            self.scrollView.contentSize = CGSizeMake(MTScreenW, self.curPageView.height+self.bakPageView.height);
            [self scrollToContentOffset:CGPointMake(0, self.curPageView.height-kScrollHeight) isTapClick:NO];
        }
            break;
            
        case 0://显示当前
        {
            [self resetView];//防止重绘时出现文字重叠
            CGRect cFrame = [self frameOfChaptercontent:cchapterContent];
            self.curPageView.frame = cFrame;
            
            self.curChapterContent = cchapterContent;
            [self loadView:self.curPageView content:cchapterContent];
            
            self.scrollView.contentSize = CGSizeMake(MTScreenW, self.curPageView.height);
            
            float y = cpercent>=0?(cpercent*(self.curPageView.height-kScrollHeight)):0;
            CGPoint point = CGPointMake(0,y);
            [self.scrollView setContentOffset:point animated:NO];
        }
            break;
            
        case 1://往后
        {//显示上一章和当前章
            CGRect pFrame = [self frameOfChaptercontent:pchapterContent];
            CGRect cFrame = [self frameOfChaptercontent:cchapterContent];
            self.bakPageView.frame = pFrame;
            cFrame.origin.y = pFrame.size.height;
            self.curPageView.frame = cFrame;
            self.bakChapterContent = pchapterContent;
            self.curChapterContent = cchapterContent;
            [self loadView:self.bakPageView content:pchapterContent];
            [self loadView:self.curPageView content:cchapterContent];
            
            CGPoint offset = CGPointMake(0, cFrame.origin.y);
            
            self.scrollView.contentSize = CGSizeMake(MTScreenW, self.bakPageView.height+self.curPageView.height);
            [self scrollToContentOffset:offset isTapClick:NO complete:^{
                if (needResumeTimer && !_isForceStop) {//需要继续自动阅读，并且下一章有内容
                    _autoScrollReadingTimer = [NSTimer scheduledTimerWithTimeInterval:self.timerInterval target:self selector:@selector(autoScrollReadingWithUpdown:) userInfo:nil repeats:YES];
                }
            }];
        }
            break;
        default:
            break;
    }
    
    [self.footerView updateProgressPercent:cpercent>=0?cpercent:0];

};

- (void)setScrollContentOffSet:(CGPoint)point {
    
    [_scrollView setContentOffset:CGPointMake(0, _scrollView.contentOffset.y+point.y) animated:YES];
}

- (void)initScrollViewContentOffset:(CGPoint)point {
    
    [_scrollView setContentOffset:CGPointMake(0, point.y)];
}

- (void)scrollContentOffset {
    
    [_scrollView setContentOffset:CGPointMake(0, _scrollView.contentOffset.y+kScrollHeight)];
}

- (CGSize)pageContentSize {
    
    return _scrollView.contentSize;
}

- (CGPoint)pageContentOffSet {
    
    return _scrollView.contentOffset;
}

- (NSString *)content {
    
    return [self.curChapterContent.chaptercontent stringByReplacingOccurrencesOfString:@"\0" withString:@""];
}

-(void)loadView:(PageView *)view content:(ChapterContent *)chapterContent{
    
    [view setText:[self attributedString:chapterContent]];
}

-(void)scrollToContentOffset:(CGPoint)point isTapClick:(BOOL)tap{
    [self scrollToContentOffset:point isTapClick:tap complete:nil];
}

-(void)scrollToContentOffset:(CGPoint)point isTapClick:(BOOL)tap complete:(void(^)(void))complete{
    
    if(tap){//手动点击的时候自定义动画
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                _scrollView.contentOffset=point;
                if(complete)complete();
            }];
        });
    }else{//系统滑动手势移动时使用系统的动画滚动方法
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_scrollView setContentOffset:point animated:YES];
            
            _scrollView.scrollEnabled=NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//滚动到下一章头部时暂停滚动一会，防止多次滑动滑过头
                _scrollView.scrollEnabled=YES;
                if(complete)complete();
            });
        });
    }
}

//滚动翻页
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    BOOL isPre = scrollView.contentOffset.y<0;
    BOOL isNext = scrollView.contentSize.height-scrollView.contentOffset.y<MTScreenH;
    if(isPre||isNext){
        if([self.delegate respondsToSelector:@selector(pageScrollVerticalView:shouldSkipChapterIspre:)]){
            [self.delegate pageScrollVerticalView:self shouldSkipChapterIspre:isPre];
            MTLog(@"滑动翻页send delegate ====");
        }
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
   
    if ([self.delegate respondsToSelector:@selector(pageScrollVerticalView:scrollViewDidEndDecelerating:)]) {
        [self.delegate pageScrollVerticalView:self scrollViewDidEndDecelerating:scrollView];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    self.tapAction.enabled = YES;
    
    CGPoint offset = scrollView.contentOffset;
    float percent = 0;//当前阅读百分比
    float offSetInCurrent = 0;//当前阅读偏移
    float viewHeight = 1;//当前阅读视图的高度
    
    BOOL onlyCurrentOne = self.curPageView.y==0&&self.curPageView.height==self.scrollView.contentSize.height;//当前只有scrollView中只有curPageView这一个视图
    BOOL hasTwoAndCurrentFront = (self.curPageView.height<self.scrollView.contentSize.height)&&self.curPageView.y==0;//两个视图，curPageView在前
    BOOL hasTwoAndCurrentBehind = self.curPageView.y!=0;//两个视图，curPageView在后//&&offset.y>self.bakPageView.height&&offset.y<self.scrollView.contentSize.height当前显示的是后面的那个视图
    
    if (onlyCurrentOne) {
        offSetInCurrent = offset.y;
        viewHeight = [self getViewheightAndSetBookmark:YES];
    }else if(hasTwoAndCurrentFront){
        if (offset.y<self.curPageView.height) {//当前显示的是前面的curPageView视图
            offSetInCurrent = offset.y;
            viewHeight = [self getViewheightAndSetBookmark:YES];
        }else{//当前显示的是后面的bakPageView视图
            offSetInCurrent = offset.y-self.curPageView.height;
            viewHeight = [self getViewheightAndSetBookmark:NO];
        }
    }else if(hasTwoAndCurrentBehind){
        if (offset.y>=self.bakPageView.height&&offset.y<self.scrollView.contentSize.height) {//当前显示的是后面的curPageView视图
            offSetInCurrent = offset.y-self.bakPageView.height;
            viewHeight = [self getViewheightAndSetBookmark:YES];
        }else{
            offSetInCurrent = offset.y;
            viewHeight = [self getViewheightAndSetBookmark:NO];
        }
    }
    
    percent = viewHeight>0?(offSetInCurrent/viewHeight):0;
    percent = percent>1?(self.curPageView.y==self.scrollView.contentOffset.y?0:1):percent;//显示最后一页时是百分百，第一页是百分之零
    self.bookmark.percent = [NSString stringWithFormat:@"%f",percent];
    [self.footerView updateProgressPercent:percent];
}

-(float)getViewheightAndSetBookmark:(BOOL)iscurrent{
    
    float height = 0;
    if (iscurrent) {
        self.bookmark.bookid = self.curChapterContent.bookid;
        self.bookmark.chapterid = self.curChapterContent.chapterid;
        self.bookmark.chaptername = self.curChapterContent.chaptername;
        height = self.curPageView.height-kScrollHeight;
    }else{
        self.bookmark.bookid = self.bakChapterContent.bookid;
        self.bookmark.chapterid = self.bakChapterContent.chapterid;
        self.bookmark.chaptername = self.bakChapterContent.chaptername;
        height = self.bakPageView.height-kScrollHeight;
    }
    
    return height;
}

-(CGRect)frameOfChaptercontent:(ChapterContent *)chapterContent{
    
    CGRect headFrame = CGRectMake([ReaderGlobalModel shareModel].readerConfig.padingLeft, 0, kTextWidth, [self getAttributedStringHeightWithString:[self attributedString:chapterContent] WidthValue:kTextWidth]);
    
    return headFrame;
}

-(NSAttributedString *)attributedString:(ChapterContent *)chapterContent{
    
    if(!chapterContent.chaptercontent)return nil;
    NSString *content = [chapterContent.chaptername stringByAppendingFormat:@"\n%@\n",chapterContent.chaptercontent];
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:content attributes:[ReaderGlobalModel shareModel].attributes];
    return attrText;
}

- (int)getAttributedStringHeightWithString:(NSAttributedString *)string  WidthValue:(int) width
{
    if(!string)return 0;
    CGFloat heightValue = 0;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
    
    CGFloat height = 100000; //这里的高要设置足够大
    CGRect drawingRect = CGRectMake(0, 0, width, height);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, drawingRect);
    CTFrameRef textFrame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0,0), path, NULL);
    CFArrayRef lines = CTFrameGetLines(textFrame);
    CGPoint lineOrigins[CFArrayGetCount(lines)];
    CTFrameGetLineOrigins(textFrame, CFRangeMake(0, 0), lineOrigins);
    
    //最后一行原点y坐标加最后一行下行行高跟行距
    CGFloat line_y = (CGFloat)lineOrigins[CFArrayGetCount(lines)-1].y;  //最后一行line的原点y坐标
    CGFloat lastAscent = 0;//上行行高
    CGFloat lastDescent = 0;//下行行高
    CGFloat lastLeading = 0;//行距
    CTLineRef lastLine = CFArrayGetValueAtIndex(lines, CFArrayGetCount(lines)-1);
    CTLineGetTypographicBounds(lastLine, &lastAscent, &lastDescent, &lastLeading);
    //height - line_y为除去最后一行的字符原点以下的高度，descent + leading为最后一行不包括上行行高的字符高度
    CGPathRelease(path);
    CFRelease(framesetter);
    CFRelease(textFrame);
    heightValue = height - line_y + (CGFloat)(fabs(lastDescent) + lastLeading);
    //    heightValue = CGFloat_ceil(heightValue);
    heightValue += 120;//章节末尾留一些空白
    
    return heightValue;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    CGPoint point = [touch locationInView:self];
    if (((point.x < MTScreenW/3 && point.y < MTScreenH*3/4) || point.y < MTScreenH/4) || ((point.x > MTScreenW*2/3 && point.y > MTScreenH/4) || point.y > MTScreenH*3/4)) {
        return YES;
    }
    return NO;
}

//手势点击事件
- (void)tapOnPageView:(UITapGestureRecognizer *)tap {
    
    CGPoint point = [tap locationInView:self];
    [self tapOnPoint:point];
}

//自动翻页滚到下一屏
- (void)autoRead{
    
    CGPoint point = CGPointMake(MTScreenW-50, MTScreenH-100);;
    [self tapOnPoint:point];
}

//自动阅读定时器间隔
-(float)timerInterval{
    
    NSInteger speed =  11-[ReaderGlobalModel shareModel].readerConfig.autoReadingSpeed;
    //0.06  0.15
    float interval = 0.05+speed*0.01;
    return interval;
}

//自动滚动
- (void)autoScrollRead {
    
    [self stopAutoScrollReadForce:NO];
    _autoScrollReadingTimer = [NSTimer scheduledTimerWithTimeInterval:self.timerInterval target:self selector:@selector(autoScrollReadingWithUpdown:) userInfo:nil repeats:YES];
}

- (void)autoScrollReadingWithUpdown:(NSTimer *)timer {
    
    CGFloat y = [ReaderGlobalModel shareModel].readerConfig.autoReadingSpeed*3;
    [self autoReadSetScrollContentOffSet:CGPointMake(0, y)];
    
    if (self.pageContentSize.height-self.pageContentOffSet.y<kScrollHeight) {
        //切换下一章
        if([self.delegate respondsToSelector:@selector(pageScrollVerticalView:shouldSkipChapterIspre:)]){
            [self.delegate pageScrollVerticalView:self shouldSkipChapterIspre:NO];
        }
        [self stopAutoScrollReadForce:NO];
        needResumeTimer = YES;
    }
}

- (void)stopAutoScrollReadForce:(BOOL)force {
    
    _isForceStop = force;
    [_autoScrollReadingTimer invalidate];
    _autoScrollReadingTimer = nil;
}

//自动翻页一点点滚动
- (void)autoReadSetScrollContentOffSet:(CGPoint)offSet {
    [_scrollView setContentOffset:CGPointMake(0, _scrollView.contentOffset.y+offSet.y) animated:YES];
}

//点击屏幕上的某个点
-(void)tapOnPoint:(CGPoint)point{
    
    CGPoint offset = _scrollView.contentOffset;
    float y = 0;
    BOOL isTurnPage=NO;//本次滚动是否需要进行翻页操作
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kSetClipLeftPageDown]) {
        y = offset.y + kScrollHeight;
        if (y+0.3*kScrollHeight>=self.scrollView.contentSize.height) {//滚到底了,y值添加三分之一的偏移，防止滚动出空白页
            y = self.scrollView.contentSize.height-kScrollHeight;
            if([self.delegate respondsToSelector:@selector(pageScrollVerticalView:shouldSkipChapterIspre:)]){
                isTurnPage = YES;
                [self.delegate pageScrollVerticalView:self shouldSkipChapterIspre:NO];
            }
        }
        if(!isTurnPage){
            [self scrollToContentOffset:CGPointMake(offset.x,y) isTapClick:YES];
        }
    } else {
        if (((point.x < MTScreenW/3 && point.y < MTScreenH*3/4) || point.y < MTScreenH/4)) {//前滚
            y = offset.y - kScrollHeight;
            if (y<0) {//滚到头了
                y=0;
                if([self.delegate respondsToSelector:@selector(pageScrollVerticalView:shouldSkipChapterIspre:)]){
                    isTurnPage = YES;
                    [self.delegate pageScrollVerticalView:self shouldSkipChapterIspre:YES];
                }
            }
            
            if(!isTurnPage){
                [self scrollToContentOffset:CGPointMake(offset.x,y) isTapClick:YES];
            }
        }else if ((point.x > MTScreenW*2/3 && point.y > MTScreenH/4) || point.y > MTScreenH*3/4) {//后滚
            
            y = offset.y + kScrollHeight;
            if (y+0.3*kScrollHeight>=self.scrollView.contentSize.height) {//滚到底了,y值添加三分之一的偏移，防止滚动出空白页
                y = self.scrollView.contentSize.height-kScrollHeight;
                if([self.delegate respondsToSelector:@selector(pageScrollVerticalView:shouldSkipChapterIspre:)]){
                    isTurnPage = YES;
                    [self.delegate pageScrollVerticalView:self shouldSkipChapterIspre:NO];
                }
            }
            if(!isTurnPage){
                [self scrollToContentOffset:CGPointMake(offset.x,y) isTapClick:YES];
            }
        }
    }
   
}

#pragma mark - PageScrollFooterView
- (PageScrollFooterView *)footerView {
    
    if (!_footerView) {
        _footerView = [[PageScrollFooterView alloc] init];
    }
    return _footerView;
}

- (void)resetColor {
    
    [self.footerView resetColor];
}

- (void)menuShow:(BOOL)isshow{
    
    self.scrollView.scrollEnabled = !isshow;//外面菜单显示时不可以滚动
    self.tapAction.numberOfTouchesRequired = isshow?10:1;
}

-(void)dealloc{
    
    [self stopAutoScrollReadForce:NO];//销毁定时器
    self.scrollView.delegate = nil;
    self.tapAction.delegate = nil;
    self.tapAction = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
